/*
 * @lc app=leetcode.cn id=24 lang=typescript
 *
 * [24] 两两交换链表中的节点
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */
//  思路：迭代
//  利用dummy节点，调换后续节点注意顺序

//  复杂度： O(n) O(1)

function swapPairs(head: ListNode | null): ListNode | null {
    let newHead = new ListNode()
    newHead.next = head
    let curr: ListNode = newHead
    while (curr.next && curr.next.next) {
        let node1: ListNode = curr.next
        let node2: ListNode = curr.next.next
        curr.next = node2
        node1.next = node2.next
        node2.next = node1
        // 此时已经翻转 node1为后面的那个
        curr = node1
    }
    return newHead.next
};
// @lc code=end

import { ListNode } from './type'
let head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))))
console.log(ListNode.printList(swapPairs(head)))
